package com.ruoyi.web.controller.admin.app;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.admin.domain.LlmAppSettings;
import com.ruoyi.admin.service.app.LlmAppSettingsService;
import com.ruoyi.common.core.domain.AjaxResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 * 应用设置前端控制器
 * </p>
 *
 * @author author
 * @since 2025-08-12
 */
@Slf4j
@RestController
@RequestMapping("/knowledge/api/appSettings")
//@Api(tags = "应用设置相关接口")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class LlmAppSettingsController {

    @Autowired
    private LlmAppSettingsService llmAppSettingsService;


    //    @ApiOperation(value = "新增应用设置")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody LlmAppSettings llmAppSettings) {
        return llmAppSettingsService.addAppSetting(llmAppSettings);
    }

    //    @ApiOperation(value = "删除应用设置")
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Integer id) {
        try {
            boolean result = llmAppSettingsService.removeById(id);
            return result ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
        } catch (Exception e) {
            log.error("删除应用设置失败", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "更新应用设置")
    @PutMapping("/update")
    public AjaxResult update(@RequestBody LlmAppSettings llmAppSettings) {
        return llmAppSettingsService.updateAppSetting(llmAppSettings);
    }

    //    @ApiOperation(value = "根据ID查询应用设置")
    @GetMapping("/select/{id}")
    public AjaxResult findById(@PathVariable Integer id) {
        try {
            LlmAppSettings appSettings = llmAppSettingsService.getById(id);
            return AjaxResult.success("查询成功", appSettings);
        } catch (Exception e) {
            log.error("查询应用设置失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "根据名称查询应用设置")
    @GetMapping("/selectByName/{name}")
    public AjaxResult findByName(@PathVariable String name) {
        try {
            LlmAppSettings appSettings = llmAppSettingsService.getAppSettingsByName(name);
            return AjaxResult.success("查询成功", appSettings);
        } catch (Exception e) {
            log.error("根据名称查询应用设置失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "分页查询应用设置")
    @GetMapping("/page")
    public AjaxResult page(LlmAppSettings llmAppSettings,
                           @RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "50") Integer size) {
        try {
            IPage<LlmAppSettings> pageRes = llmAppSettingsService.getByPage(page, size, llmAppSettings);
            return AjaxResult.success("查询成功", pageRes);
        } catch (Exception e) {
            log.error("分页查询应用设置失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "根据类型查询应用设置列表")
    @GetMapping("/listByType/{type}")
    public AjaxResult listByType(@PathVariable String type) {
        try {
            List<LlmAppSettings> list = llmAppSettingsService.getAppSettingsByType(type);
            return AjaxResult.success("查询成功", list);
        } catch (Exception e) {
            log.error("根据类型查询应用设置失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "根据启用状态查询应用设置列表")
    @GetMapping("/listByEnable/{enable}")
    public AjaxResult listByEnable(@PathVariable String enable) {
        try {
            List<LlmAppSettings> list = llmAppSettingsService.getAppSettingsByEnable(enable);
            return AjaxResult.success("查询成功", list);
        } catch (Exception e) {
            log.error("根据启用状态查询应用设置失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "获取应用设置总数")
    @GetMapping("/count")
    public AjaxResult getCount() {
        try {
            long count = llmAppSettingsService.count();
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            log.error("获取应用设置总数失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "发布应用")
    @PutMapping("/publish/{id}")
    public AjaxResult publishApp(@PathVariable Integer id) {
        try {
            // 先检查应用是否存在
            LlmAppSettings app = llmAppSettingsService.getById(id);
            if (app == null) {
                return AjaxResult.error("应用不存在");
            }

            // 检查应用是否已经发布
            if (Boolean.TRUE.equals(app.getRelease())) {
                return AjaxResult.error("应用已经发布");
            }

            boolean result = llmAppSettingsService.publishApp(id);
            return result ? AjaxResult.success("发布成功") : AjaxResult.error("发布失败");
        } catch (Exception e) {
            log.error("发布应用失败", e);
            return AjaxResult.error("发布失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "取消发布应用")
    @PutMapping("/unpublish/{id}")
    public AjaxResult unpublishApp(@PathVariable Integer id) {
        try {
            // 先检查应用是否存在
            LlmAppSettings app = llmAppSettingsService.getById(id);
            if (app == null) {
                return AjaxResult.error("应用不存在");
            }

            // 检查应用是否已经取消发布
            if (Boolean.FALSE.equals(app.getRelease()) || app.getRelease() == null) {
                return AjaxResult.error("应用已经取消发布");
            }

            boolean result = llmAppSettingsService.unpublishApp(id);
            return result ? AjaxResult.success("取消发布成功") : AjaxResult.error("取消发布失败");
        } catch (Exception e) {
            log.error("取消发布应用失败", e);
            return AjaxResult.error("取消发布失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "批量发布应用")
    @PutMapping("/batchPublish")
    public AjaxResult batchPublishApps(@RequestBody List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return AjaxResult.error("应用ID列表不能为空");
            }

            boolean result = llmAppSettingsService.batchPublishApps(ids);
            return result ? AjaxResult.success("批量发布成功") : AjaxResult.error("批量发布失败");
        } catch (Exception e) {
            log.error("批量发布应用失败", e);
            return AjaxResult.error("批量发布失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "批量取消发布应用")
    @PutMapping("/batchUnpublish")
    public AjaxResult batchUnpublishApps(@RequestBody List<Integer> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return AjaxResult.error("应用ID列表不能为空");
            }

            boolean result = llmAppSettingsService.batchUnpublishApps(ids);
            return result ? AjaxResult.success("批量取消发布成功") : AjaxResult.error("批量取消发布失败");
        } catch (Exception e) {
            log.error("批量取消发布应用失败", e);
            return AjaxResult.error("批量取消发布失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "切换应用发布状态")
    @PutMapping("/toggleRelease/{id}")
    public AjaxResult toggleAppRelease(@PathVariable Integer id) {
        try {
            // 先检查应用是否存在
            LlmAppSettings app = llmAppSettingsService.getById(id);
            if (app == null) {
                return AjaxResult.error("应用不存在");
            }

            boolean result = llmAppSettingsService.toggleAppRelease(id);
            if (result) {
                // 获取切换后的状态
                LlmAppSettings updatedApp = llmAppSettingsService.getById(id);
                String statusMsg = Boolean.TRUE.equals(updatedApp.getRelease()) ? "已发布" : "已取消发布";
                return AjaxResult.success("切换成功，当前状态：" + statusMsg);
            } else {
                return AjaxResult.error("切换失败");
            }
        } catch (Exception e) {
            log.error("切换应用发布状态失败", e);
            return AjaxResult.error("切换失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "根据发布状态查询应用设置列表")
    @GetMapping("/listByRelease")
    public AjaxResult listByRelease(@RequestParam Boolean release) {
        try {
            List<LlmAppSettings> list = llmAppSettingsService.getAppSettingsByRelease(release);
            return AjaxResult.success("查询成功", list);
        } catch (Exception e) {
            log.error("根据发布状态查询应用设置失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "获取已发布应用列表")
    @GetMapping("/listPublished")
    public AjaxResult listPublishedApps() {
        try {
            List<LlmAppSettings> list = llmAppSettingsService.getAppSettingsByRelease(true);
            return AjaxResult.success("查询成功", list);
        } catch (Exception e) {
            log.error("获取已发布应用列表失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    //    @ApiOperation(value = "获取未发布应用列表")
    @GetMapping("/listUnpublished")
    public AjaxResult listUnpublishedApps() {
        try {
            List<LlmAppSettings> list = llmAppSettingsService.getAppSettingsByRelease(false);
            return AjaxResult.success("查询成功", list);
        } catch (Exception e) {
            log.error("获取未发布应用列表失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }


    //    @ApiOperation(value = "上传应用图标")
    @PostMapping("/uploadAppIcon")
    public AjaxResult uploadAppIcon(@RequestParam("file") MultipartFile file) {

        String url = llmAppSettingsService.uploadAppIcon(file);

        return AjaxResult.success("上传成功", url);
    }


    //    @ApiOperation(value = "删除应用图标")
    @PostMapping("/removeAppIcon")
    public AjaxResult removeAppIcon(@RequestParam("url") String url) {

        llmAppSettingsService.removeAppIcon(url);

        return AjaxResult.success("删除成功", url);
    }

    @GetMapping("/getGatewayPermissions")
    public AjaxResult getGatewayPermissions() {
        return llmAppSettingsService.getGatewayPermissions();
    }

}
